<?php
/**
 * (logic)
 */
namespace App\Logic\File\Profit;

use App\Models\File\FileProfit;
use App\Util\RExcel;
use Illuminate\Support\Facades\DB;
class ParseFile
{
    /**
     * 解析 财务上传的月销售报表核算文件
     */
    public static function parse(){
        try{
            $parseFile = FileProfit::query()->where('status',1)->first();
            if(!$parseFile)die(0);
            DB::beginTransaction();
            if($parseFile->user_id != 1){
                $parseFile->status = 2;
                $parseFile->save();
                DB::commit();
            }else{
                $flag = self::_parseFiles($parseFile);
                if($flag){
                    $parseFile->status = 2;
                    $parseFile->save();
                    DB::commit();
                }else{
                    DB::rollBack();
                }
            }
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }

    /**
     * 解析文件
     * @param $parseFile
     * @return bool|int
     */
    private static function _parseFiles($parseFile){
        $file = self::_getParseFilePath($parseFile);
        if(!is_file($file))return false;
        ini_set('memory_limit', '2048M');
        set_time_limit(0);
        $lines = RExcel::importSheet($file);
        unset($lines[0]);
        $flag = (self::$_class[$parseFile->file_type])::exeParse($lines,$parseFile->file_date);
        return $flag;
    }

    //（临时类,创建临时数据）
    private static $_class = [
        1 => ParsePSalesFile::class,            //Payment销售额（临时）
        2 => ParsePReFeeFile::class,            //Payment退货费（临时）
        3 => ParsePThFeeFile::class,            //Payment第三方发货FBA费（临时）
        4 => ParsePCoFeeFile::class,            //Amazon月仓储费（临时）
        5 => ParseMonthlyStorageFile::class,    //MonthlyStorage月储存费（临时）
        6 => ParseLongTermStorageFile::class,   //LongTermStorage长期存储费（临时）
        7 => ParsePIcFeeFile::class,            //Payment库存补偿费（临时）
        8 => ParseRemovalOrderFile::class,      //RemovalOrderDetail移除订单（临时）
        9 => ParsePRmFeeFile::class,            //Payment移除费（临时）
        10 => ParseAdsFile::class,              //Advertised广告费（临时）
        11 => ParseVCampaignFile::class,        //VideoCampaign视频广告（临时）
        12 => ParseBCampaignFile::class,        //BrandsCampaign品牌/店铺广告（临时）
        13 => ParseInventoryEventFile::class,   //InventoryEventDetail库存（临时）
        14 => ParsePTotalFile::class,           //Payment-Total总额（临时）
        15 => ParseThAdsFile::class,            //第三方广告费（临时）
        16 => ParseVATFile::class,              //VAT费（临时）
        17 => ParseDSPFile::class,              //DSP（临时）
        18 => ParsePCPlanFile::class            //Payment清库计划费用（临时）
    ];

    /**
     * 获取文件路径
     * @param $parseFile
     * @return string
     */
    private static function _getParseFilePath($parseFile){
        $fileDir = FileProfit::fileDir(strtotime($parseFile->file_date));
        $fileName = FileProfit::fileName($parseFile->file_type,$parseFile->user_id,$parseFile->file_name);
        return public_uploads_path($fileDir).DIRECTORY_SEPARATOR.$fileName;
    }

    /**
     * 匹配SKU
     * @param $str
     * @return string
     */
    public static function matchSku($str){
        return matchSkuByCampaign($str);
    }

    public static function getTranslationType($translationType,$country){
        if(!$translationType)return '';
        $translationType = trim($translationType);
        $translationTypes = self::_translationType($country);
        if(!$translationTypes)return $translationType;
        if($country == 'FR'){
            $translationType = replaceSpecChar($translationType);
        }
        if (array_key_exists($translationType, $translationTypes) ){
            $translationType = $translationTypes[$translationType];
        }else{
            if($country == 'ES'){
                if (strpos($translationType, 'inventario') > 0) {
                    $translationType = 'FBA Inventory Fee';
                }elseif(strpos($translationType, 'servicio') > 0){
                    $translationType = 'Service Fee';
                }else{
                    $translationType = 'Cannot find '.$translationType;
                }
            }elseif($country == 'FR'){
                if (strpos($translationType, 'stock') > 0) {
                    $translationType = 'FBA Inventory Fee';
                }else{
                    $translationType = 'Cannot find '.$translationType;
                }
            }else{
                $translationType = 'Cannot find '.$translationType;
            }
        }
        return $translationType;
    }

    protected static function _translationType($country){
        if(in_array($country,['DE','IT','FR','ES','TR','NL','PL','UK','MX','BR','BE','JP'])){
            return self::${'_translationType_'.$country};
        }else{
            return null;
        }
    }

    private static $_translationType_DE = [
        'Anpassung' => 'Adjustment',
        'Bestellung' => 'Order',
        'Bestellung_Wiedereinzug' => 'Order',
        'Erstattung_Wiedereinzug' => 'Order',
        'Erstattung' => 'Refund',
        'Servicegebühr' => 'Service Fee',
        'Versand durch Amazon Lagergebühr' => 'FBA Inventory Fee',
        'Übertrag' => 'Transfer',
        'Blitzangebotsgebühr' => 'Lightning Deal Fee',
        'Verbindlichkeit' =>'Adjustment',
        'Liquidationen' =>'Liquidations',
    ];

    private static $_translationType_IT = [
        'Modifica' => 'Adjustment',
        'Ordine' => 'Order',
        'Order_Retrocharge' => 'Order',
        'Rimborso' => 'Refund',
        'Commissione di servizio' => 'Service Fee',
        'Costo di stoccaggio Logistica di Amazon' => 'FBA Inventory Fee',
        'Trasferimento' => 'Transfer',
        'Tariffa dell’Offerta Lampo' => 'Lightning Deal Fee',
        'Saldo negativo' => 'Debt',
        'Liquidazioni' => 'Liquidations',
    ];

    private static $_translationType_FR = [
        'Ajustement' => 'Adjustment',
        'Commande' => 'Order',
        'Order_Retrocharge' => 'Order',
        'Remboursement' => 'Refund',
        'Frais de service' => 'Service Fee',
        'Frais de stock Expédié par Amazon' => 'FBA Inventory Fee',
        'Transfert' => 'Transfer',
        'Tarif de la Vente Flash' => 'Lightning Deal Fee',
        'Solde negatif' => 'Debt'
    ];

    private static $_translationType_ES = [
        'Ajuste' => 'Adjustment',
        'Pedido' => 'Order',
        'Reembolso' => 'Refund',
        'Tarifa de prestación de servicio' => 'Service Fee',
        'Tarifas de inventario de Logística de Amazon' => 'FBA Inventory Fee',
        'Transferir' => 'Transfer',
        'Tarifa de Oferta flash' => 'Lightning Deal Fee',
        'Liquidaciones' =>'Liquidations',
    ];

    private static $_translationType_TR = [
        'Sipariş' => 'Order',
        'Sipari' => 'Order',
    ];

    private static $_translationType_NL = [
        'Bestelling' => 'Order',
    ];

    private static $_translationType_PL = [
        'Zamówienie' => 'Order',
    ];

    private static $_translationType_UK = [
        'Adjustment' => 'Adjustment',
        'Order' => 'Order',
        'Order_Retrocharge' => 'Order',
        'Refund' => 'Refund',
        'Service Fee' => 'Service Fee',
        'FBA Inventory Fee' => 'FBA Inventory Fee',
        'Transfer' => 'Transfer',
        'Lightning Deal Fee' => 'Lightning Deal Fee',
        'Liquidations Adjustments' => 'Liquidations',
        'Liquidations' => 'Liquidations',
    ];

    private static $_translationType_MX = [
        'Pedido' => 'Order',
        'Tarifa de servicio' => 'Service Fee',
    ];

    private static $_translationType_BR = [
        'Pedido' => 'Order',
        'Tarifa de servicio' => 'Service Fee',
    ];

    private static $_translationType_BE = [
        'Commande' => 'Order',
    ];

    private static $_translationType_JP = [
        '調整' => 'Adjustment',
        '注文' => 'Order',
        '返金' => 'Refund',
        '注文外料金' => 'Service Fee',
        'FBA 在庫関連の手数料' => 'FBA Inventory Fee',
        '振込み' => 'Transfer',
        'FBA Customer Return Fee' => 'FBA Customer Return Fee',
        '数量限定タイムセール手数料' => 'Lightning Deal Fee'
    ];
}
